import { checkPermissions } from './permission'

// 保存图片
export const saveImage = function (url, callback) {
  if (url) {
    // #ifdef MP-WEIXIN
    if (checkPermissions('album')) {
      uni.showLoading({
        title: this.$t('utils_uni_media_msg_e4090eb7'),
      })
      uni.downloadFile({
        url: url,
        success: (data) => {
          if (data.statusCode == 200) {
            uni.saveImageToPhotosAlbum({
              filePath: data.tempFilePath,
              success: () => {
                uni.hideLoading()
                callback && callback()
                uni.showToast({
                  title: this.$t('utils_libs_QuShe-SharerPoster_QS-SharePoster_app_msg_3b108349'),
                })
              },
              fail(e) {
                uni.hideLoading()
                uni.showToast({
                  title: '下载失败，错误原因：' + e.errMsg,
                  icon: 'none',
                })
              },
            })
          } else {
            uni.hideLoading()
            uni.showToast({
              title: this.$t('utils_uni_media_msg_65e200d3'),
              icon: 'none',
            })
          }
        },
        fail(e) {
          uni.hideLoading()
          uni.showToast({
            title: '下载失败，错误原因：' + e.errMsg,
            icon: 'none',
          })
        },
      })
    }
    // #endif
    // #ifdef H5
    uni.showLoading({
      title: this.$t('utils_uni_media_msg_e4090eb7'),
    })
    uni.downloadFile({
      url: url,
      success: (data) => {
        uni.hideLoading()
        if (data.statusCode == 200) {
          callback && callback()
          window.open(data.tempFilePath)
        } else {
          uni.showToast({
            title: this.$t('utils_uni_media_msg_65e200d3'),
            icon: 'none',
          })
        }
      },
      fail(e) {
        uni.hideLoading()
        uni.showToast({
          title: '下载失败，错误原因：' + e.errMsg,
          icon: 'none',
        })
      },
    })
    // #endif
    // #ifdef APP-PLUS
    if (checkPermissions('album')) {
      uni.showLoading({
        title: this.$t('utils_uni_media_msg_e4090eb7'),
      })
      uni.saveImageToPhotosAlbum({
        filePath: url,
        success: () => {
          uni.hideLoading()
          callback && callback()
          uni.showToast({
            title: this.$t('utils_libs_QuShe-SharerPoster_QS-SharePoster_app_msg_3b108349'),
          })
        },
        fail(e) {
          uni.hideLoading()
          uni.showToast({
            title: '下载失败，错误原因：' + e.errMsg,
            icon: 'none',
          })
        },
      })
    }
    // #endif
  } else {
    uni.showToast({
      title: this.$t('utils_uni_media_msg_e0efb732'),
      icon: 'none',
    })
  }
}
